public class OverrideHospitalBudgetNew
{
    public String msg{get;set;}
    public Boolean ForUpdate;
    public Boolean ForAllocate{get;set;}
    public Boolean DisplaySave{get;set;} // display Save button or not
    public String MSRSelect{get;set;}
    public String HosSelect{get;set;}
    public String HosCode{get;set;}
    public String HosClass{get;set;}
    public Decimal CityTotalKG{get;set;}
    public Decimal CityTotalRMB{get;set;}
    public Decimal LMTotalUsedKG{get;set;}
    public Decimal LMTotalUsedRMB{get;set;}    
    public Decimal ThisHosTotalUsedKG{get;set;}
    public Decimal ThisHosTotalUsedRMB{get;set;} 
    Hospital__c HospitalInfo = new Hospital__c(); 
    public List<String> ProductNames = new List<String>();
    public List<Product2> ProductOrgList = new List<Product2>();
    String Colum1;
    String Colum2;
    String Colum3;
    String Colum4;
    String Colum5;
    String Colum6;
    String Colum7;

    String Product1;
    String Product2;
    String Product3;
    String Product4;
    String Product5;
    String Product6;
    String Product7;
    
    public class My1Exception extends Exception {} 
    

    List<HospitalMonthlyAllocation__c> ExistHMA = new List<HospitalMonthlyAllocation__c>();
    List<HospitalAllocationItem__c> ExistHAI = new List<HospitalAllocationItem__c>();
    List<HospitalMonthlyAllocationItem__c> ExistHMAI = new List<HospitalMonthlyAllocationItem__c>();               
    public CityBudget__c CityBudget{
         get{
             if(CityBudget== null)
                 CityBudget = new CityBudget__c();
             return CityBudget;
         }
         set;
    }
    public List<HospitalAllocation__c> HospitalBudgets{
         get{
             if(HospitalBudgets== null)
                 HospitalBudgets= new List<HospitalAllocation__c>();
             return HospitalBudgets;
         }
         set;
    }    
           

    public List<TableItemControl> TotalNumber{
         get{
             if(TotalNumber== null)
                 TotalNumber= new List<TableItemControl>();
             return TotalNumber;
         }
         set;
    }         
        
    public List<TableItemControl> TableItemsDown{         
        get{
             if(TableItemsDown== null)
                 TableItemsDown= new List<TableItemControl>();
             return TableItemsDown;
         }
        set;
    }    
    
    public String UrlId
    {
        get{        
            return System.currentPageReference().getParameters().get('id');     
           }  
        set;
    }  
    User cu  = [Select Name,UserRoleId,ProfileId,Title__c,ManagerId From User Where Id =:UserInfo.getUserId()];
    UserRole ur = [Select Id,Name,ParentRoleId  From UserRole Where Id =: cu.UserRoleId]; 
    List<AggregateResult> CityMonBud = [Select sum(BudgetKg__c)Kg, Month__c Mon From CityMonthlyBudget__c Where CityBudget__c =: UrlId Group by Month__c];
    
    public List<SelectOption> MSRs
    {
        get
        {
            if(MSRs == null)
                MSRs = new List<SelectOption>();
            
            return MSRs;                      
        }
        set;
    }    
    
    public List<SelectOption> Hospitals
    {
        get
        {
            if(Hospitals == null)
                Hospitals = new List<SelectOption>();
            
            return Hospitals;                      
        }
        set;
    } 
    RecordType BudgetRecord = [Select r.Name, r.Id From RecordType r Where Name =: 'Hospital Monthly Budget'];
    RecordType ItemBudgetRecord = [Select r.Name, r.Id From RecordType r Where Name =: 'Hospital Allocation Item Budget'];
        
    public void UpdateCityAllocatedNumber()
    {
        List<AggregateResult> TotalCityHeadUsedKg = [Select sum(TotalKG__c)TotalKg,sum(TotalRMB__c)TotalRMB  From HospitalAllocation__c Where CityBudget__c =: UrlId ]; 
        LMTotalUsedKG = (Decimal)TotalCityHeadUsedKg[0].get('TotalKg');
        if(LMTotalUsedKG == null)
        {
            LMTotalUsedKG = 0;
        }   
        LMTotalUsedRMB = (Decimal)TotalCityHeadUsedKg[0].get('TotalRMB'); 
        if(LMTotalUsedRMB == null)
        {
            LMTotalUsedRMB = 0;
        }                 
    }
    public void UpdateHospitalAllocatedNumber(Id HosId)
    {
        List<AggregateResult> TotalCityHeadUsedKg = [Select sum(TotalKG__c)TotalKg,sum(TotalRMB__c)TotalRMB  From HospitalAllocation__c Where CityBudget__c =: UrlId and Hospital__c =: HosId]; 
        ThisHosTotalUsedKG = (Decimal)TotalCityHeadUsedKg[0].get('TotalKg');
        if(ThisHosTotalUsedKG == null)
        {
            ThisHosTotalUsedKG = 0;
        }   
        ThisHosTotalUsedRMB = (Decimal)TotalCityHeadUsedKg[0].get('TotalRMB'); 
        if(ThisHosTotalUsedRMB == null)
        {
            ThisHosTotalUsedRMB = 0;
        }                 
    }    
     
    public PageReference  MsrActionSupport()
    { 
        List<Hospital__c> HosList = [Select id,Nickname__c,Name From Hospital__c Where City__c =: CityBudget.place__c and ownerid =: msrSelect and (Active__c =: true or (Active__c =: false and approvalstatus__c = '审批通过但未生效'))];
        Hospitals.clear();
        Hospitals.add(new SelectOption('1',''));
        for(Hospital__c hos : HosList)
        {
            Hospitals.add(new SelectOption(hos.id,hos.Nickname__c));
        }
        return null;
    }
     
    public PageReference  HosActionSupport()
    { 
        ForUpdate = false;   
        TotalNumber = new list<TableItemControl>();
        TableItemsDown = new list<TableItemControl>();
        TableItemControl Amount = new TableItemControl();
        Double TotalSubRegion =0;
        
        UpdateHospitalAllocatedNumber(HosSelect);

        
        HospitalInfo = [Select class__c, ownerid, Name,id,Nickname__c, HospitalCode__c From Hospital__c where Id  =: HosSelect]; 
        HosCode = HospitalInfo.HospitalCode__c;
        HosClass = HospitalInfo.class__c;
        
        List<HospitalAllocation__c> ExistHA = [Select h.Year__c, h.SubRegion__c, h.Region__c, h.Place__c, h.OwnerId, 
            h.Name, h.LineManager__c,h.Id, h.Hospital__c, h.HospitalCode__c,
            h.CityBudget__c, h.Area__c From HospitalAllocation__c h where h.CityBudget__c =: CityBudget.id and h.Hospital__c =: HospitalInfo.id];
        
        Decimal totalConversion = 0;   
        if(ExistHA.size()>0){
            ForUpdate = true;
            ExistHMA = [Select h.Year__c, h.SubRegion__c, h.SalesCity__c, h.Region__c, h.Rate__c, h.PE_KG_Conversion_num__c, 
                        h.Name, h.Month__c, h.LineManager__c,  h.Id, h.Hospital__c, h.HospitalTotalRMBAdjusted__c, 
                        h.HospitalTotalKGAdjusted__c, h.HospitalCode__c, h.HospitalAllocation__c,  h.CityBudget__c, h.Area__c From HospitalMonthlyAllocation__c h 
                        Where h.HospitalAllocation__c =: ExistHA[0].id];
            ExistHAI = [Select h.Year__c, h.SubRegion__c, h.SalesCity__c, h.Region__c, h.Rate__c, h.HospitalAllocation__c,
                        h.RMB__c, h.Product__c, h.Place__c, h.Name, h.LineManager__c,h.KG__c, h.Id, 
                        h.Area__c From HospitalAllocationItem__c h where h.HospitalAllocation__c =: ExistHA[0].id];
            ExistHMAI = [Select h.unit__c, h.Year__c, h.SubRegion__c, h.SalesCity__c, h.Region__c, h.Rate__c, h.RMB__c, h.Product__c, h.Name, h.LineManager__c,  
                        h.KG__c, h.Id, h.HospitalMonthlyAllocation__c, h.HospitalAllocationItem__c, h.Area__c,h.Product__r.Name,
                        h.Month__c,Product__r.Product_Unit_Volume__c From HospitalMonthlyAllocationItem__c h where h.HospitalAllocation__c =: string.valueof(ExistHA[0].id).substring(0,15)];
            
            for(Integer i = 1; i < 13;i++) // put 12 monthes to table
            {
                TableItemControl T = new TableItemControl();
                T.Str = CityBudget.SalesCity__c;
                T.HMA.Hospital__c = HospitalInfo.id;
                T.Str2 = HospitalInfo.Nickname__c;
                T.Str1 = String.valueof(i);
                T.Int8 = 0;
      
                for(HospitalMonthlyAllocationItem__c h : ExistHMAI)
                {
                    if(h.Month__c == string.valueof(i)){
                        if(h.Product__r.Name == Product1)
                        {
                            T.Int1 = Integer.valueof(h.unit__c);
                        }
                        if(h.Product__r.Name == Product2)
                        {
                            T.Int2 = Integer.valueof(h.unit__c);
                        }
                        if(h.Product__r.Name == Product3)
                        {
                            T.Int3 = Integer.valueof(h.unit__c);
                        }
                        if(h.Product__r.Name == Product4)
                        {
                            T.Int4 = Integer.valueof(h.unit__c);
                        }
                        if(h.Product__r.Name == Product5)
                        {
                            T.Int5 = Integer.valueof(h.unit__c);
                        }
                        if(h.Product__r.Name == Product6)
                        {
                            T.Int6 = Integer.valueof(h.unit__c);
                        }
                        if(h.Product__r.Name == Product7)
                        {
                            T.Int7 = Integer.valueof(h.unit__c);
                        }  
                    }                  
                }

            List<AggregateResult> HospitalThisYearPEConversion = [Select sum(PE_Conversion_forecast__c)TotalIn,Month__c Mon  From 
                                          Achieve__c Where PE_Conversion_forecast__c > 0 and   Year__c =: string.valueof(CityBudget.Year__c) and Hospital_Name__c =: HospitalInfo.id group by Month__c];
                   
                for(AggregateResult ag : HospitalThisYearPEConversion)
                {
                    if(Integer.valueof(ag.get('Mon'))== i)
                    {
                        T.Dec1 = (Decimal)ag.get('TotalIn');
                        if((Decimal)ag.get('TotalIn') > 0)
                        {
                            totalConversion += (Decimal)ag.get('TotalIn');
                        }
                    }
                }

                for(AggregateResult ag : CityMonBud)
                {
                    if(Integer.valueof(ag.get('Mon'))== i)
                    {
                        List<AggregateResult> TotalHosMonBud = [Select sum(KG__c) Kg From HospitalMonthlyAllocation__c Where HospitalAllocation__r.CityBudget__c =: UrlId  and SalesCity__c =: CityBudget.Place__c and Month__c =: String.valueof(ag.get('Mon'))];
                        if(TotalHosMonBud.size() > 0)
                            T.MonbudSurplus = (Decimal)ag.get('Kg') - (Decimal)TotalHosMonBud[0].get('Kg');
                        else
                            T.MonbudSurplus = 0;
                        TotalSubRegion += T.MonbudSurplus;                        
                    }
                }

                TableItemsDown.add(T);
            }                 
                
            TableItemControl total = new TableItemControl();
            TotalNumber.add(total);
            TotalNumber[0].Str = CityBudget.SalesCity__c;
            TotalNumber[0].HMA.Hospital__c = HospitalInfo.id;
            TotalNumber[0].Str2 = HospitalInfo.Nickname__c;
            TotalNumber[0].Str1 = '全年';
            TotalNumber[0].Int8 = 0;
            TotalNumber[0].Dec1 = totalConversion;
            TotalNumber[0].MonbudSurplus = TotalSubRegion;
     
            for(TableItemControl t : TableItemsDown)
            {
                if(t.Dec1 > 0)
                    TotalNumber[0].Dec1 += t.Dec1;
                                
                if((TotalNumber[0].Int1 != null)&&(TotalNumber[0].Int1 >= 0))
                    TotalNumber[0].Int1 += t.Int1;
                else
                    TotalNumber[0].Int1 = t.Int1;
                    
                if((TotalNumber[0].Int2 != null)&&(TotalNumber[0].Int2 >= 0))
                    TotalNumber[0].Int2 += t.Int2;
                else
                    TotalNumber[0].Int2 = t.Int2;
                    
                if((TotalNumber[0].Int3 != null)&&(TotalNumber[0].Int3 >= 0))
                    TotalNumber[0].Int3 += t.Int3;
                else
                    TotalNumber[0].Int3 = t.Int3;
                    
                if((TotalNumber[0].Int4 != null)&&(TotalNumber[0].Int4 >= 0))
                    TotalNumber[0].Int4 += t.Int4;
                else
                    TotalNumber[0].Int4 = t.Int4;
                    
                if((TotalNumber[0].Int5 != null)&&(TotalNumber[0].Int5 >= 0))
                    TotalNumber[0].Int5 += t.Int5;
                else
                    TotalNumber[0].Int5 = t.Int5;
                    
                if((TotalNumber[0].Int6 != null)&&(TotalNumber[0].Int6 >= 0))
                    TotalNumber[0].Int6 += t.Int6;
                else
                    TotalNumber[0].Int6 = t.Int6;
                    
                if((TotalNumber[0].Int7 != null)&&(TotalNumber[0].Int7 >= 0))
                    TotalNumber[0].Int7 += t.Int7;
                else
                    TotalNumber[0].Int7 = t.Int7;             
            }
            
            TableItemControl TT = new TableItemControl();
            TT.Str = CityBudget.SalesCity__c;
            TT.Str2 = HospitalInfo.Nickname__c;           
            TT.Str1  = '全年';
            TT.Int8 = TotalNumber[0].Int8;
            TT.Int1 = TotalNumber[0].Int1;
            TT.Int2 = TotalNumber[0].Int2;
            TT.Int3 = TotalNumber[0].Int3;
            TT.Int4 = TotalNumber[0].Int4;
            TT.Int5 = TotalNumber[0].Int5;
            TT.Int6 = TotalNumber[0].Int6;
            TT.Int7 = TotalNumber[0].Int7;
            TT.Int8 = TotalNumber[0].Int8 ;
            TT.Dec1 = TotalNumber[0].Dec1 ; 
            TT.MonbudSurplus = TotalNumber[0].MonbudSurplus;           
          
            TableItemsDown.add(TT);         
        }
        else{
            for(Integer i = 1; i < 13;i++) // put 12 monthes to table
            {
                TableItemControl T = new TableItemControl();
                T.Str = CityBudget.SalesCity__c;
                T.HMA.Hospital__c = HospitalInfo.id;
                T.Str2 = HospitalInfo.Nickname__c;
                T.Str1 = String.valueof(i);
                T.Int8 = 0;
                T.Int1 = 0;
                T.Int2 = 0;
                T.Int3 = 0;
                T.Int4 = 0;
                T.Int5 = 0;
                T.Int6 = 0;
                T.Int7 = 0;
                List<AggregateResult> HospitalThisYearPEConversion = [Select sum(PE_Conversion_forecast__c)TotalIn,Month__c Mon  From 
                                              Achieve__c Where PE_Conversion_forecast__c > 0 and   Year__c =: string.valueof(CityBudget.Year__c) and Hospital_Name__c =: HospitalInfo.id group by Month__c];
                       
                for(AggregateResult ag : HospitalThisYearPEConversion)
                {
                    if(Integer.valueof(ag.get('Mon'))== i)
                    {
                        T.Dec1 = (Decimal)ag.get('TotalIn');
                        if((Decimal)ag.get('TotalIn') > 0)
                        {
                            totalConversion += (Decimal)ag.get('TotalIn');
                        }
                    }
                }
                for(AggregateResult ag : CityMonBud)
                {
                    if(Integer.valueof(ag.get('Mon'))== i)
                    {
                        List<AggregateResult> TotalHosMonBud = [Select sum(KG__c) Kg From HospitalMonthlyAllocation__c Where HospitalAllocation__r.CityBudget__c =: UrlId  and SalesCity__c =: CityBudget.Place__c and Month__c =: String.valueof(ag.get('Mon'))];
                        if(TotalHosMonBud.size() > 0)
                        {
                            if(TotalHosMonBud[0].get('Kg') != null)
                                T.MonbudSurplus = (Decimal)ag.get('Kg') - (Decimal)TotalHosMonBud[0].get('Kg');
                            else
                                T.MonbudSurplus = (Decimal)ag.get('Kg');
                        }
                            
                        else
                            T.MonbudSurplus = (Decimal)ag.get('Kg');
                        TotalSubRegion += T.MonbudSurplus;                        
                    }
                }                 
                                           
                TableItemsDown.add(T);
            }        

            TableItemControl total = new TableItemControl();
            TotalNumber.add(total);
            TotalNumber[0].Str = CityBudget.SalesCity__c;
            TotalNumber[0].HMA.Hospital__c = HospitalInfo.id;
            TotalNumber[0].Str2 = HospitalInfo.Nickname__c;
            TotalNumber[0].Str1 = '全年';
            TotalNumber[0].Int1 = 0;
            TotalNumber[0].Int2 = 0;
            TotalNumber[0].Int3 = 0;
            TotalNumber[0].Int4 = 0;
            TotalNumber[0].Int5 = 0;
            TotalNumber[0].Int6 = 0;
            TotalNumber[0].Int7 = 0;
            TotalNumber[0].Int8 = 0;
            TotalNumber[0].Dec1 = totalConversion;
            TotalNumber[0].MonbudSurplus = TotalSubRegion;             

            TableItemControl TT = new TableItemControl();
            TT.Str = CityBudget.SalesCity__c;
            TT.Str2 = HospitalInfo.Nickname__c;           
            TT.Str1  = '全年';
            TT.Int8 = TotalNumber[0].Int8;
            TT.Int1 = TotalNumber[0].Int1;
            TT.Int2 = TotalNumber[0].Int2;
            TT.Int3 = TotalNumber[0].Int3;
            TT.Int4 = TotalNumber[0].Int4;
            TT.Int5 = TotalNumber[0].Int5;
            TT.Int6 = TotalNumber[0].Int6;
            TT.Int7 = TotalNumber[0].Int7;
            TT.Int8 = TotalNumber[0].Int8 ;
            TT.Dec1 = TotalNumber[0].Dec1 ;
            TT.MonbudSurplus = TotalNumber[0].MonbudSurplus;             
          
            TableItemsDown.add(TT);
        }
        return null;
    }       
    
    
    public OverrideHospitalBudgetNew(){
    
        DisplaySave = true;    
        ForUpdate = false;
        Colum1 = '安婴儿A+无乳糖配方400g(罐)';
        Colum2 = '安婴儿A+200g(盒)';
        Colum3 = '安婴儿A+400g(罐)';
        Colum4 = '安婴儿A+早产儿配方400g(罐)';
        Colum5 = '安婴儿A+早产儿配方59ml(瓶)';
        Colum6 = '无苯丙氨酸配方454g(罐)';
        Colum7 = '安婴乐450g(罐)';
        
        Product1 = '安婴儿A+无乳糖400克罐装（样品）';
        Product2 = '安婴儿A+200克盒装（样品）';
        Product3 = '安婴儿A+400克罐装（样品）';
        Product4 = '安婴儿A+早产儿配方奶粉400克罐装（样品）';
        Product5 = '安婴儿A+早产儿配方奶59毫升×6瓶装（样品）';
        Product6 = '美赞臣无苯丙氨酸配方粉（1阶段）454克罐装';
        Product7 = '安婴乐450克罐装（样品）';        
        
        ProductNames.add(Product1);
        ProductNames.add(Product2);
        ProductNames.add(Product3);
        ProductNames.add(Product4);
        ProductNames.add(Product5);
        ProductNames.add(Product6);
        ProductNames.add(Product7);
        
        ProductOrgList = [Select id, name From Product2 Where name in: ProductNames];
        
                
        CityBudget = [Select c.SubRegionBudget__r.PE_Sample_Management__c,c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c,c.AfterAdjustmentKG__c,
                c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, 
                 c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c, c.AfterAdjustmentRMB__c,c.Approved__c,
                c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name,c.Id,  c.Area__c From CityBudget__c c Where 
                c.id =: UrlId];
        if(integer.valueof(CityBudget.Year__c) > date.today().year())
        {
            ForAllocate = true;
        }
        else
        {
            ForAllocate = false;
        }        
        UpdateCityAllocatedNumber();

       
        List<User> subList = [Select Name,UserRoleId,Title__c From User Where Id =:UserInfo.getUserId() and IsActive=:true];
        if(subList.size() > 0){
            Boolean haveflag = false;
            User currentRole = subList.get(0);
            MSRs.add(new SelectOption('1',''));
            List<User> u = [Select Id,UserRoleId,Title__c From User Where Title__c = 'Sales Rep' and FunctionDepartment__c ='Medical Sales' and IsActive=:true];
            if(u.size() > 0)
            {
                if(currentRole.UserRoleId != u.get(0).UserRoleId){           
                    List<UserRole> sur1 = [Select Id,Name From UserRole Where ParentRoleId =: currentRole.UserRoleId];
                    List<User> secondLine = new List<User>();                   
                    for(UserRole urole:sur1){
                        List<User> sub1 = [Select Alias,Id,Name,UserRoleId,Title__c  From User Where UserRoleId  =: urole.Id and IsActive=:true];                                                           
                        for(User user:sub1){
                            haveflag = true;
                            secondLine.add(user);
                            MSRs.add(new SelectOption(user.id,user.Alias));
                        }
                    }
                    Boolean loopflag = true; 
                    Boolean firsttime = true;
                    List<User> NextUser = new List<User>();
                    List<User> ComUser = new List<User>();
                    
                    while(loopflag){
                        if(secondLine.size() > 0)
                        {                                                                 
                            List<UserRole> NextRole = [Select Id,Name From UserRole Where ParentRoleId =: secondLine.get(0).UserRoleId];
                            List<ID> NextRoleId = new List<ID>();
                            for(UserRole ur : NextRole ){
                                NextRoleId.add(ur.Id);
                            }
                            if(NextRole.size() <= 0){
                                break;
                            }                                                                            
                            NextUser = [Select Alias,Id,Name,UserRoleId,Title__c From User Where UserRoleId  in: NextRoleId and IsActive=:true];
                            for(User add : NextUser)
                            {
                                List<UserRole> curRole = [Select Id,Name From UserRole Where Id =: add.UserRoleId]; 
                                MSRs.add(new SelectOption(add .id,add .Alias));
                                secondLine = NextUser.clone();                                
                            }
                            if(NextUser.get(0).Title__c == 'Sales Rep')
                            {
                                break;
                            }                                               
                        }                                          
                    }
                }  
            }
        }
        if(!CityBudget.Approved__c)
        {
            DisplaySave = false;         
        }
        
    }
    
    public void SetRecord(Boolean Submit)
    {
        if(ForUpdate)
        {
            for(TableItemControl ti : TableItemsDown)
            {
                List<HospitalMonthlyAllocationItem__c> UpdateHMAI = new List<HospitalMonthlyAllocationItem__c>();
                for(HospitalMonthlyAllocationItem__c h : ExistHMAI)
                {
                    if(h.Month__c == ti.Str1){
                        if(h.Product__r.name == Product1)
                        {
                            h.unit__c = ti.Int1;
                            h.KG__c = integer.valueof(h.Product__r.Product_Unit_Volume__c) * h.unit__c/1000;
                            UpdateHMAI.add(h);
                            continue;
                        }
                        if(h.Product__r.name == Product2)
                        {
                            h.unit__c = ti.Int2;
                            h.KG__c = integer.valueof(h.Product__r.Product_Unit_Volume__c) * h.unit__c/1000;
                            UpdateHMAI.add(h);
                            continue;
                        }                    
                        if(h.Product__r.name == Product3)
                        {
                            h.unit__c = ti.Int3;
                            h.KG__c = integer.valueof(h.Product__r.Product_Unit_Volume__c) * h.unit__c/1000;
                            UpdateHMAI.add(h);
                            continue;
                        }                    
                        if(h.Product__r.name == Product4)
                        {
                            h.unit__c = ti.Int4;
                            h.KG__c = integer.valueof(h.Product__r.Product_Unit_Volume__c) * h.unit__c/1000;
                            UpdateHMAI.add(h);
                            continue;
                        }                    
                        if(h.Product__r.name == Product5)
                        {
                            h.unit__c = ti.Int5;
                            
                            UpdateHMAI.add(h);
                            continue;
                        }                    
                        if(h.Product__r.name == Product6)
                        {
                            h.unit__c = ti.Int6;
                            h.KG__c = integer.valueof(h.Product__r.Product_Unit_Volume__c) * h.unit__c/1000;
                            UpdateHMAI.add(h);
                            continue;
                        }                    
                        if(h.Product__r.name == Product7)
                        {
                            h.unit__c = ti.Int7;
                            h.KG__c = integer.valueof(h.Product__r.Product_Unit_Volume__c) * h.unit__c/1000;
                            UpdateHMAI.add(h);
                            continue;
                        }                       
                    }
                }
                
                update UpdateHMAI;
            }            
               
        }
        else{
            // create Hospital Allocation data
            HospitalAllocation__c HospitalAllocationNew = new HospitalAllocation__c();
            HospitalAllocationNew.Ownerid = HospitalInfo.ownerid;
            HospitalAllocationNew.CityBudget__c = CityBudget.Id;
            HospitalAllocationNew.HospitalCode__c = HospitalInfo.HospitalCode__c;
            HospitalAllocationNew.LineManager__c = cu.ManagerId;
            HospitalAllocationNew.Place__c = CityBudget.Place__c;
            HospitalAllocationNew.Hospital__c = HospitalInfo.id;
            HospitalAllocationNew.name = CityBudget.Year__c + '年'+ HospitalInfo.Nickname__c + '样品管理分配';
            HospitalAllocationNew.PESampleManagement__c = CityBudget.SubRegionBudget__r.PE_Sample_Management__c;
            insert HospitalAllocationNew;
            
            // create Hospital Allocation Item data
            
            List<HospitalAllocationItem__c> InsertHAI = new List<HospitalAllocationItem__c>();
            for(Product2 p : ProductOrgList)
            {
                HospitalAllocationItem__c HospitalAllocationItemNew = new HospitalAllocationItem__c();
                HospitalAllocationItemNew.Product__c = p.id;
                HospitalAllocationItemNew.Place__c = CityBudget.Place__c;
                HospitalAllocationItemNew.RecordTypeId = ItemBudgetRecord.id;
                HospitalAllocationItemNew.HospitalAllocation__c = HospitalAllocationNew.id;
                HospitalAllocationItemNew.name = CityBudget.Year__c + '年' + p.name + '样品管理分配';
                InsertHAI.add(HospitalAllocationItemNew);
            
            }
            insert InsertHAI;
            
            // create Hospital Monthly Allocation data
            List<HospitalMonthlyAllocation__c> InsertHMA = new List<HospitalMonthlyAllocation__c>();
            for(TableItemControl t : TableItemsDown)
            {
                if(t.Str1 == '全年')
                {
                    continue;
                }
                HospitalMonthlyAllocation__c HMANew = new HospitalMonthlyAllocation__c();
                HMANew = t.HMA;
                HMANew.SalesCity__c = CityBudget.Place__c;
                HMANew.RecordTypeId = BudgetRecord.id; 
                HMANew.Month__c = t.Str1; 
                HMANew.HospitalAllocation__c = HospitalAllocationNew.id;
                HMANew.Hospital__c = HospitalInfo.id;
                HMANew.name = CityBudget.Year__c + '年'+ t.Str1 + '月' + HospitalInfo.Nickname__c + '样品管理分配';
                InsertHMA.add(HMANew);
            }
            insert InsertHMA;        
            
           // create Hospital Monthly Allocation Item data
           List<String> IdHAI = new List<String>();
           for(HospitalAllocationItem__c hmi : InsertHAI)
           {
               IdHAI.add(hmi.id); 
           }
           List<HospitalAllocationItem__c> GetHAI = [Select id,Product__r.name,Product__r.Product_Unit_Volume__c from HospitalAllocationItem__c Where id in: IdHAI];
           
            for(TableItemControl ti : TableItemsDown)
            {
                List<HospitalMonthlyAllocationItem__c> insertHMAI = new List<HospitalMonthlyAllocationItem__c>();
                
                HospitalMonthlyAllocationItem__c HMAI1st = new HospitalMonthlyAllocationItem__c();
                for(HospitalAllocationItem__c h : GetHAI)
                {
                    if(h.Product__r.name == Product1)
                    {
                        HMAI1st.HospitalAllocationItem__c = h.id;
                        HMAI1st.Product__c = h.Product__c;
                        HMAI1st.unit__c = ti.Int1;
                        HMAI1st.KG__c = integer.valueof(h.Product__r.Product_Unit_Volume__c) * HMAI1st.unit__c/1000;
                        break;
                    }
                }
                for(HospitalMonthlyAllocation__c h :InsertHMA){
                    
                    if(h.Month__c == ti.Str1){
                        HMAI1st.HospitalMonthlyAllocation__c = h.id;
                        HMAI1st.SalesCity__c = CityBudget.Place__c;
                        HMAI1st.name = CityBudget.Year__c + '年'+ ti.Str1 + '月' + Product1;
                        insertHMAI.add(HMAI1st);
                        break;
                    } 
                }
                
                HospitalMonthlyAllocationItem__c HMAI2nd = new HospitalMonthlyAllocationItem__c();
                for(HospitalAllocationItem__c h : GetHAI)
                {
                    if(h.Product__r.name == Product2)
                    {
                        HMAI2nd.HospitalAllocationItem__c = h.id;
                        HMAI2nd.Product__c = h.Product__c; 
                        HMAI2nd.unit__c = ti.Int2;
                        HMAI2nd.KG__c = integer.valueof(h.Product__r.Product_Unit_Volume__c) * HMAI2nd.unit__c/1000;
                        break;
                    }
                } 
                for(HospitalMonthlyAllocation__c h :InsertHMA){
                    if(h.Month__c == ti.Str1){
                        HMAI2nd.HospitalMonthlyAllocation__c = h.id;
                        HMAI2nd.SalesCity__c = CityBudget.Place__c;
                        HMAI2nd.name = CityBudget.Year__c + '年'+ ti.Str1 + '月' + Product2;
                        insertHMAI.add(HMAI2nd);                        
                        break;
                    } 
                }
            
                HospitalMonthlyAllocationItem__c HMAI3th = new HospitalMonthlyAllocationItem__c();
                for(HospitalAllocationItem__c h : GetHAI)
                {
                    if(h.Product__r.name == Product3)
                    {
                        HMAI3th.HospitalAllocationItem__c = h.id;
                        HMAI3th.Product__c = h.Product__c; 
                        HMAI3th.unit__c = ti.Int3;
                        HMAI3th.KG__c = integer.valueof(h.Product__r.Product_Unit_Volume__c) * HMAI3th.unit__c/1000;
                        break;
                    }
                } 
                for(HospitalMonthlyAllocation__c h :InsertHMA){
                    if(h.Month__c == ti.Str1){
                        HMAI3th.HospitalMonthlyAllocation__c = h.id;
                        HMAI3th.SalesCity__c = CityBudget.Place__c;
                        HMAI3th.name = CityBudget.Year__c + '年'+ ti.Str1 + '月' + Product3;
                        insertHMAI.add(HMAI3th);                    
                        break;
                    } 
                }
    
                
                HospitalMonthlyAllocationItem__c HMAI4th = new HospitalMonthlyAllocationItem__c();
                for(HospitalAllocationItem__c h : GetHAI)
                {
                    if(h.Product__r.name == Product4)
                    {
                        HMAI4th.HospitalAllocationItem__c = h.id;
                        HMAI4th.Product__c = h.Product__c; 
                        HMAI4th.unit__c = ti.Int4;
                        HMAI4th.KG__c = integer.valueof(h.Product__r.Product_Unit_Volume__c) * HMAI4th.unit__c/1000;
                        break;
                    }
                } 
                for(HospitalMonthlyAllocation__c h :InsertHMA){
                    if(h.Month__c == ti.Str1){
                        HMAI4th.HospitalMonthlyAllocation__c = h.id;
                        HMAI4th.SalesCity__c = CityBudget.Place__c;
                        HMAI4th.name = CityBudget.Year__c + '年'+ ti.Str1 + '月' + Product4;
                        insertHMAI.add(HMAI4th);                       
                        break;
                    } 
                }
     
                
                HospitalMonthlyAllocationItem__c HMAI5th = new HospitalMonthlyAllocationItem__c();
                for(HospitalAllocationItem__c h : GetHAI)
                {
                    if(h.Product__r.name == Product5)
                    {
                        HMAI5th.HospitalAllocationItem__c = h.id;
                        HMAI5th.Product__c = h.Product__c; 
                        HMAI5th.unit__c = ti.Int5;
                       
                        break;
                    }
                } 
                for(HospitalMonthlyAllocation__c h :InsertHMA){
                    if(h.Month__c == ti.Str1){
                        HMAI5th.HospitalMonthlyAllocation__c = h.id;
                        HMAI5th.SalesCity__c = CityBudget.Place__c;
                        HMAI5th.name = CityBudget.Year__c + '年'+ ti.Str1 + '月' + Product5;
                        insertHMAI.add(HMAI5th);                      
                        break;
                    } 
                }
                        
                
                HospitalMonthlyAllocationItem__c HMAI6th = new HospitalMonthlyAllocationItem__c();
                for(HospitalAllocationItem__c h : GetHAI)
                {
                    if(h.Product__r.name == Product6)
                    {
                        HMAI6th.HospitalAllocationItem__c = h.id;
                        HMAI6th.Product__c = h.Product__c; 
                        HMAI6th.unit__c = ti.Int6;
                        HMAI6th.KG__c = integer.valueof(h.Product__r.Product_Unit_Volume__c) * HMAI6th.unit__c/1000;
                        break;
                    }
                } 
                for(HospitalMonthlyAllocation__c h :InsertHMA){
                    if(h.Month__c == ti.Str1){
                        HMAI6th.HospitalMonthlyAllocation__c = h.id;
                        HMAI6th.SalesCity__c = CityBudget.Place__c;
                        HMAI6th.name = CityBudget.Year__c + '年'+ ti.Str1 + '月' + Product6;
                        insertHMAI.add(HMAI6th);                       
                        break;
                    } 
                }
        
                
                HospitalMonthlyAllocationItem__c HMAI7th = new HospitalMonthlyAllocationItem__c();
                for(HospitalAllocationItem__c h : GetHAI)
                {
                    if(h.Product__r.name == Product7)
                    {
                        HMAI7th.HospitalAllocationItem__c = h.id;
                        HMAI7th.Product__c = h.Product__c; 
                        HMAI7th.unit__c = ti.Int7;
                        HMAI7th.KG__c = integer.valueof(h.Product__r.Product_Unit_Volume__c) * HMAI7th.unit__c / 1000;
                        break;
                    }
                } 
                for(HospitalMonthlyAllocation__c h :InsertHMA){
                    if(h.Month__c == ti.Str1){
                        HMAI7th.HospitalMonthlyAllocation__c = h.id;
                        HMAI7th.SalesCity__c = CityBudget.Place__c;
                        HMAI7th.name = CityBudget.Year__c + '年'+ ti.Str1 + '月' + Product7;
                        insertHMAI.add(HMAI7th);                       
                        break;
                    } 
                }
                insert insertHMAI;         
            }
            ForUpdate = true;
        }
        
    }

    public void Allocate()
    {
        
    }
    
    public PageReference Save()
    {

        SetRecord(false);        

        UpdateCityAllocatedNumber();
        UpdateHospitalAllocatedNumber(HosSelect);
        return null;

        
    }

    public PageReference Cancel()
    {
        pageReference pr = new pageReference('/'+ UrlId);     
        pr.setredirect(true);      
        return pr;
    }
    
    static testMethod void OverrideViewTest()
    {
       Profile p  = [select id from profile where name =: GlobalProperties.ProfileASM ];
        UserRole SRMMM_SOC = [Select Id,Name From UserRole Where Name =: GlobalProperties.RoleSOCRGM ];
        
        User u1 = new User (alias = 'standt', email = 'shuaicao@isoftstone.com', emailencodingkey='UTF-8',UserRoleId = SRMMM_SOC.id,
                lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', Title__c = 'Sales Rep',profileid = p.id, 
                timezonesidkey = 'America/Los_Angeles', username='asdfdaa@testorg1.com');
        insert u1;
        
        System.runAs(u1) {
            PE_Sample_Management__c PE = new PE_Sample_Management__c();
            PE.WOC_Total_budget_RMB__c = 1;
            PE.Deal__c = true;
            PE.WOC_budget_allocation_kg__c = 2;
            PE.WOCInMarketValueHide__c = 0;
            PE.WOCConversionForcast__c = 0;                  
            PE.SOC_Total_budget_RMB__c = 0;
            PE.SOC_budget_allocation_kg__c = 0;
            PE.SOCInMarketValueHide__c = 0;
            PE.SOCConversionForcast__c = 0;                  
            PE.EOC_Total_budget_RMB__c = 0;
            PE.EOC_budget_allocation_kg__c = 0;
            PE.EOCInMarketValueHide__c = 0;
            PE.EOCConversionForcast__c = 0;            
            PE.NOC_Total_budget_RMB__c = 0;
            PE.NOC_budget_allocation_kg__c = 0;
            PE.NOCInMarketValueHide__c = 0;
            PE.NOCConversionForcast__c = 0;
            PE.Rate__c =2;
            PE.Total_Budget_Allocation_RMB__c = 1;
            insert PE;
            
            RegionalBudget__c RB = new RegionalBudget__c();
            RB.PESampleManagement__c = PE.id;
            RB.Approved__c = true;
            RB.ApprovalStatus__c = '审批通过';
            insert RB;
            
            Sub_Region_Budget__c SRB = new Sub_Region_Budget__c();
            SRB.PE_Sample_Management__c = PE.id;
            SRB.RegionalBudget__c = RB.id;
            SRB.Name = '2012年华南一区专业样品管理';
            insert SRB;
            
            CityBudget__c CB = new CityBudget__c();
            CB.SubRegionBudget__c = SRB.id;
            insert CB;
            
            test.setCurrentPageReference(Page.OverrideSubRegionBudgetNew);
            System.currentPageReference().getParameters().put('id', CB.Id);          
            
            OverrideHospitalBudgetNew testCase = new OverrideHospitalBudgetNew();
            Hospital__c Hos = [Select id From Hospital__c limit 1];
            testCase.MsrActionSupport();
            testCase.HosSelect = Hos.id;
            testCase.HosActionSupport();

            testCase.Save();
            testCase.Cancel();  
        }      
    }
 
}